import { createSlice, type PayloadAction } from '@reduxjs/toolkit'

// 定义用户数据类型（与后端字段对齐，保留可选以兼容不同接口）
export interface UserInfo {
  id?: string
  userId?: number
  email?: string
  username?: string
  nickName?: string
  avatar?: string
  headPic?: string
  phone?: string
  sessionId?: string
  age?: number
  sex?: number
  height?: number
  weight?: number
  bankFlag?: number
  faceFlag?: number
  idCardFlag?: number
  whetherBingWeChat?: number
  jiGuangPwd?: string
  [key: string]: unknown // 允许其他字段
}

// 将接口返回数据标准化为 UserInfo
export const normalizeUserFromApi = (apiUser?: Record<string, unknown> | null): UserInfo => {
  const src = (apiUser ?? {}) as Record<string, unknown>
  const user: UserInfo = {
    id: (src as any)?.id ?? undefined,
    userId: (src as any)?.userId ?? undefined,
    email: (src as any)?.email ?? undefined,
    username: (src as any)?.username ?? undefined,
    nickName: (src as any)?.nickName ?? undefined,
    avatar: (src as any)?.avatar ?? undefined,
    headPic: (src as any)?.headPic ?? undefined,
    phone: (src as any)?.phone ?? undefined,
    sessionId: (src as any)?.sessionId ?? undefined,
    age: (src as any)?.age ?? undefined,
    sex: (src as any)?.sex ?? undefined,
    height: (src as any)?.height ?? undefined,
    weight: (src as any)?.weight ?? undefined,
    bankFlag: (src as any)?.bankFlag ?? undefined,
    faceFlag: (src as any)?.faceFlag ?? undefined,
    idCardFlag: (src as any)?.idCardFlag ?? undefined,
    whetherBingWeChat: (src as any)?.whetherBingWeChat ?? undefined,
    jiGuangPwd: (src as any)?.jiGuangPwd ?? undefined,
  }
  return user
}

// 定义用户状态类型
interface UserState {
  userInfo: UserInfo | null
  isLoggedIn: boolean
  token: string | null
  loading: boolean
}

// 初始状态
const initialState: UserState = {
  userInfo: null,
  isLoggedIn: false,
  token: null,
  loading: false
}

// 创建用户slice
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 设置用户信息
    setUserInfo: (state, action: PayloadAction<UserInfo>) => {
      state.userInfo = action.payload
      state.isLoggedIn = true
    },
    // 设置token
    setToken: (state, action: PayloadAction<string>) => {
      state.token = action.payload
    },
    // 登录成功（允许传入后端原始数据，内部做标准化）
    loginSuccess: (
      state,
      action: PayloadAction<{ userInfo: Partial<UserInfo> & Record<string, unknown>; token?: string }>
    ) => {
      const normalized = normalizeUserFromApi(action.payload.userInfo)
      state.userInfo = normalized
      state.isLoggedIn = true
      // 优先使用入参 token，其次使用 sessionId 作为 token
      const token = action.payload.token ?? normalized.sessionId ?? null
      state.token = token
      state.loading = false
    },
    // 登出
    logout: (state) => {
      state.userInfo = null
      state.isLoggedIn = false
      state.token = null
      state.loading = false
    },
    // 设置加载状态
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload
    },
    // 更新用户信息
    updateUserInfo: (state, action: PayloadAction<Partial<UserInfo>>) => {
      if (state.userInfo) {
        state.userInfo = { ...state.userInfo, ...action.payload }
      }
    }
  }
})

// 导出actions
export const {
  setUserInfo,
  setToken,
  loginSuccess,
  logout,
  setLoading,
  updateUserInfo
} = userSlice.actions

// 导出reducer
export default userSlice.reducer

// 导出选择器
export const selectUserInfo = (state: { user: UserState }) => state.user.userInfo
export const selectIsLoggedIn = (state: { user: UserState }) => state.user.isLoggedIn
export const selectToken = (state: { user: UserState }) => state.user.token
export const selectUserLoading = (state: { user: UserState }) => state.user.loading
// 便捷选择器
export const selectUserId = (state: { user: UserState }) => state.user.userInfo?.userId
export const selectNickName = (state: { user: UserState }) => state.user.userInfo?.nickName
export const selectSessionId = (state: { user: UserState }) => state.user.userInfo?.sessionId
export const selectAuthHeaders = (state: { user: UserState }) => ({
  userId: state.user.userInfo?.userId,
  sessionId: state.user.userInfo?.sessionId ?? state.user.token ?? undefined,
})
